package com.yuufa.test.string;

public class IndexOfMain {

    public static void main(String[] args) {

        String source = "This except eexception will be thrown by the FileInputStream FileOutputStream"
                    + " and RandomAccessFile constructors when a file with the specified pathname does not"
                    + " exist It will also be thrown by these constructors if the file does exist but for"
                    + " some reason is inaccessible for example when an attempt is made to open a read-only file for writing";
        String target = "exception";

        int index = indexOf(source, target);

        System.out.println(index);
    }

    public static int indexOf(String source, String target) {

        char[] s = source.toCharArray();
        int slen = source.length();

        char[] t = target.toCharArray();
        int tlen = target.length();

        return indexOf(s, slen, t, tlen);
    }

    public static int indexOf(char[] s, int slen, char[] t, int tlen) {

        char first = t[0];
        int max = slen - tlen;

        for (int i = 0; i <= max; i++) {
            if (s[i] != first) {
                while (++i <= max && s[i] != first);
            }

            if (i <= max) {
                int j = i + 1;
                int end = i + tlen - 1;
                
                for (int k = 1; j <= end && t[k] == s[j]; k++, j++);
                
                if(j == (end + 1)) {
                    return i;
                }
            }
        }

        return -1;
    }
}
